import enciphered from "./v1";

// 百度api
// 老照片上色
const pickColorPhoto = ({ image, token }) => {
    return new Promise((r, j) => {
        uni.showLoading({
            title: "加载中",
        });
        uni.request({
            // #ifdef H5
            url: `/rest/2.0/image-process/v1/colourize?aipSdk=node&access_token=${token}`,
            // #endif
            // #ifndef H5
            url: `https://aip.baidubce.com/rest/2.0/image-process/v1/colourize?aipSdk=node&access_token=${token}`,
            // #endif
            method: "POST",
            header: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            data: {
                image,
            },
            sslVerify: false,
            success: res => {
                // console.log(res.data);
                if (res.data.error_code === 216202) {
                    return uni.showToast({
                        title: "图片不能大4MB",
                        icon: "none",
                    });
                }
                r(res.data);
            },
            fail: err => {
                j(err);
            },
            complete: () => {
                uni.hideLoading();
            },
        });
    });
};
// 老照片修复
const pickResetPhoto = ({ image, token, rectangle }) => {
    return new Promise((r, j) => {
        uni.showLoading({
            title: "加载中",
        });
        uni.request({
            // #ifdef H5
            url: `/rest/2.0/image-process/v1/inpainting?access_token=${token}`,
            // #endif
            // #ifndef H5
            url: `https://aip.baidubce.com/rest/2.0/image-process/v1/inpainting?access_token=${token}`,
            // #endif
            method: "POST",
            header: {
                "Content-Type": "application/json",
            },
            data: {
                image,
                rectangle,
            },
            sslVerify: false,
            success: res => {
                // console.log(res.data);
                if (res.data.error_code === 216202) {
                    return uni.showToast({
                        title: "图片不能大4MB",
                        icon: "none",
                    });
                }
                r(res.data);
            },
            fail: err => {
                j(err);
            },
            complete: () => {
                uni.hideLoading();
            },
        });
    });
};
//
const hightLightPhoto = ({ image, token }) => {
    return new Promise((r, j) => {
        uni.showLoading({
            title: "加载中",
        });
        /*
        https://aip.baidubce.com/rest/2.0/image-process/v1/image_definition_enhance?aipSdk=node&access_token=24.76d34484c82bb43d9ac8d6aee5705218.2592000.1615019376.282335-19463690?aipSdk=node
        */
        uni.request({
            // #ifdef H5
            url: `/rest/2.0/image-process/v1/image_definition_enhance?aipSdk=node&access_token=${token}?aipSdk=node`,
            // #endif
            // #ifndef H5
            url: `https://aip.baidubce.com/rest/2.0/image-process/v1/image_definition_enhance?aipSdk=node&access_token=${token}?aipSdk=node`,
            // #endif
            method: "POST",
            header: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            data: {
                image,
            },
            sslVerify: false,
            success: res => {
                if (res.data.error_code === 216202) {
                    return uni.showToast({
                        title: "图片不能大4MB",
                        icon: "none",
                    });
                }
                r(res.data);
            },
            fail: err => {
                j(err);
            },
            complete: () => {
                uni.hideLoading();
            },
        });
    });
};
/*
放大
*/
const scalePhoto = ({ image, token }) => {
    return new Promise((r, j) => {
        uni.showLoading({
            title: "加载中",
        });
        uni.request({
            // https://aip.baidubce.com/rest/2.0/image-process/v1/image_quality_enhance
            // #ifdef H5
            url: `/rest/2.0/image-process/v1/image_quality_enhance?aipSdk=node&access_token=${token}?aipSdk=node`,
            // #endif
            // #ifndef H5
            url: `https://aip.baidubce.com/rest/2.0/image-process/v1/image_quality_enhance?aipSdk=node&access_token=${token}?aipSdk=node`,
            // #endif
            method: "POST",
            header: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            data: {
                image,
            },
            sslVerify: false,
            success: res => {
                if (res.data.error_code === 216202) {
                    return uni.showToast({
                        title: "图片不能大4MB",
                        icon: "none",
                    });
                }
                r(res.data);
            },
            fail: err => {
                j(err);
            },
            complete: () => {
                uni.hideLoading();
            },
        });
    });
};

// 动漫头
const animationHead = ({ image, token }) => {
    return new Promise((r, j) => {
        uni.showLoading({
            title: "加载中",
        });
        uni.request({
            // https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime
            // #ifdef H5
            url: `/rest/2.0/image-process/v1/selfie_anime?aipSdk=node&access_token=${token}?aipSdk=node`,
            // #endif
            // #ifndef H5
            url: `https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime?aipSdk=node&access_token=${token}?aipSdk=node`,
            // #endif
            method: "POST",
            header: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            data: {
                image,
            },
            sslVerify: false,
            success: res => {
                if (res.data.error_code === 216202) {
                    return uni.showToast({
                        title: "图片不能大4MB",
                        icon: "none",
                    });
                }
                r(res.data);
            },
            fail: err => {
                j(err);
            },
            complete: () => {
                uni.hideLoading();
            },
        });
    });
};

/*

腾讯 api

*/

/* ***************************************************** */

// 人脸性别转换
const genderTransformation = async ({ url, mode = 1 }) => {
    return new Promise(async (resolve, reject) => {
        let [endpoint, action] = ["ft.tencentcloudapi.com", "SwapGenderPic"];
        let config = {
            Action: "SwapGenderPic",
            Region: "ap-shanghai",
            Url: url,
            // #ifdef APP-PLUS | H5
            RspImgType: "url",
            // #endif
            // #ifdef MP
            RspImgType: "base64",
            // #endif
            data: {
                "GenderInfos.0.Gender": mode,
            },
        };
        let { url: path } = await enciphered({ endpoint, action, config });
        // #ifdef H5
        path = path.replace(/https:\/\/ft.tencentcloudapi.com/, "tencentApi");
        // #endif
        await uni.request({
            url: path,
            method: "GET",
            sslVerify: true,
            success: ({ data: { Response }, statusCode, header }) => {
                console.log(Response, "人脸转换");
                if (Response.ResultUrl) {
                    // #ifndef MP
                    resolve(Response.ResultUrl);
                    // #endif
                }
                if (Response.ResultImage) {
                    // #ifdef MP
                    resolve("data:image/png;base64," + Response.ResultImage);
                    // #endif
                }
                if (Response.Error) {
                    let code = Response.Error.Code;
                    switchCodeError(code);
                }
            },
            fail: error => {
                reject(error);
            },
        });
    });
};

// 变老
const genderChangeAgePic = async ({ url, age = 20 }) => {
    return new Promise(async (resolve, reject) => {
        uni.showLoading({
            title: "转换中...",
            mask: true,
        });
        let [endpoint, action] = ["ft.tencentcloudapi.com", "ChangeAgePic"];
        let config = {
            Action: "SwapGenderPic",
            Region: "ap-shanghai",
            Url: url,
            // #ifdef APP-PLUS | H5
            RspImgType: "url",
            // #endif
            // #ifdef MP
            RspImgType: "base64",
            // #endif
            data: {
                "AgeInfos.0.Age": age,
            },
        };
        let { url: path } = await enciphered({ endpoint, action, config });
        // #ifdef H5
        path = path.replace(/https:\/\/ft.tencentcloudapi.com/, "tencentApi");
        // #endif
        await uni.request({
            url: path,
            method: "GET",
            sslVerify: true,
            success: ({ data: { Response }, statusCode, header }) => {
                console.log(Response, "年龄变老");
                if (Response.ResultUrl) {
                    // #ifndef MP
                    resolve(Response.ResultUrl);
                    // #endif
                }
                if (Response.ResultImage) {
                    // #ifdef MP
                    resolve("data:image/png;base64," + Response.ResultImage);
                    // #endif
                }
                if (Response.Error) {
                    let code = Response.Error.Code;
                    switchCodeError(code);
                }
            },
            fail: error => {
                reject(error);
            },
            complete: () => uni.hideLoading(),
        });
    });
};

const switchCodeError = code => {
    const toast = (title, icon, mask) => {
        uni.showToast({
            title: title,
            icon: icon ? icon : "success",
            mask: mask ? mask : true,
        });
    };
    let df = code.split(".");
    code = df[df.length - 1];
    console.log(code, "**/**");
    switch (code) {
        case "SignatureFailure":
            toast("失败，请重试~");
            break;
        case "DetectNoFace":
            toast("未检测到人脸");
            break;
        case "FaceSizeTooSmall":
            toast("人脸因太小被过滤，建议人脸分辨率不小于34*34");
            break;
        case "FreqCtrl":
            toast("操作太频繁，请稍后重试");
            break;
        case "ImageDecodeFailed":
            toast("图片解码失败");
            break;
        case "ImageDownloadError":
            toast("图片下载错误");
            break;
        case "ImageResolutionTooSmall":
            toast("图片短边分辨率太小，小于64。");
            break;
        case "InnerError":
            toast("服务内部错误，请重试");
            break;
        case "RequestTimeout":
            toast("后端服务超时");
            break;
        case "ImageSizeExceed":
            toast("图片数据太大。");
            break;
        case "NoFaceInPhoto":
            toast("图片中没有人脸。");
            break;
        case "Freeze":
            toast("帐号已被冻结。");
            break;
        case "InArrears":
            toast("帐号已欠费。");
            break;
        case "LowBalance":
            toast("余额不足。");
            break;
        case "StopUsing":
            toast("帐号已停服。");
            break;
        case "ChargeStatusException":
            toast("帐号已欠费。");
            break;
        default:
            toast("错误");
            break;
    }
};

/* ***************************************************** */

export {
    pickColorPhoto,
    hightLightPhoto,
    scalePhoto,
    animationHead,
    pickResetPhoto,
    genderTransformation,
    genderChangeAgePic,
};
